package com.nmgs.util;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Iterator;
import java.util.List;

public class Dom4jReadXml {
    public static String guiUser = "";
    public static String guiPass = "";
    public static String scriptUser = "";
    public static String scriptPass = "";

    static {
        try {
            // 创建SAXReader对象
            SAXReader reader = new SAXReader();
            // 加载xml文件
            Document dc = reader.read(new File(PathUtil.tomcatUserXMLPath));
            // 获取根节点
            Element e = dc.getRootElement();
            // 获取迭代器
            Iterator it = e.elementIterator();
            // 遍历迭代器，获取根节点信息
            while (it.hasNext()) {
                Element book = (Element) it.next();
                if (book.getName().equals("user")) {
                    List<Attribute> atts = book.attributes();
                    String userName = "";
                    String Pass = "";
                    for (Attribute att : atts) {
                        if (att.getName().equals("username")) {
                            userName = att.getValue();
                        } else if (att.getName().equals("password")) {
                            Pass = att.getValue();
                        } else if (att.getName().equals("roles") && att.getValue().equals("manager-gui")) {
                            guiUser = userName;
                            guiPass = Pass;
                        } else if (att.getName().equals("roles") && att.getValue().equals("manager-script")) {
                            scriptUser = userName;
                            scriptPass = Pass;
                        }
                    }
                }
//                Iterator itt = book.elementIterator();
//                while (itt.hasNext()) {
//                    Element b = (Element) itt.next();
//
//                    System.out.println("属性名：" + b.getName() + "属性值：" + b.getText());
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


